package cn.phecda.boot.common.lang.model;

import cn.hutool.core.util.StrUtil;
import cn.phecda.boot.common.lang.exception.BootRuntimeException;
import cn.phecda.boot.common.lang.util.EnvPropertyFinder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;

/**
 * <p> 租户策略 </p>
 *
 * @author : wanpinwei
 */
public enum TenantStrategy {

    /**
     * 独立数据库（独立schema）
     */
    DATABASE,

    /**
     * 共享数据库，共享schema
     */
    TABLE,


    ;

    public static final TenantStrategy DEFAULT = TenantStrategy.TABLE;

    public static TenantStrategy fromEnvirment(Environment env, String propertyName) {
        return fromEnvirment(env, propertyName, false);
    }

    public static TenantStrategy fromEnvirment(Environment env, String propertyName, boolean useDefault) {
        String propertyValue = EnvPropertyFinder.getString(env, propertyName);
        if (StringUtils.isBlank(propertyValue) && useDefault) {
            return DEFAULT;
        }

        if (StringUtils.isBlank(propertyValue)) {
            return null;
        }

        try {
            return TenantStrategy.valueOf(propertyValue.toUpperCase());
        } catch (NullPointerException | IllegalArgumentException e){
            throw  new BootRuntimeException(StrUtil.format("The value of [{}] is incorrect, property name [{}] supports [{}] ",
                    propertyValue, propertyName, TenantStrategy.values()));
        }
    }
}
